﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XcoAppSpaces.Contracts.Communication;
using XcoAppSpaces.Core;
using XcoAppSpaces.Core.Ports;
using System.Threading;
using NUnit.Framework;
using XcoAppSpaces.Contracts.Exceptions;
using XcoAppSpaces.Transport.Sockets;

namespace test.XcoAppSpaces.Core
{
	[TestFixture]
	public class testMsmqPersistentMessages
	{
		[Test]
		//[Repeat(20)]
		public void ServerGoesTemporarilyOffline_ReceivesPostedMessages()
		{
			int receivedMessages = 0;
			string msmqName1 = @".\private$\TestAppSpace";
			string msmqName2 = @".\private$\TestAppSpace2";

			//start server space and worker
			XcoAppSpace server = new XcoAppSpace(@"msmq.queuename=" + msmqName1 + ";msmq.disposequeue=false");
			server.Run<int>("myport", msg => Interlocked.Increment(ref receivedMessages));

			XcoAppSpace client = new XcoAppSpace(@"msmq.queuename=" + msmqName2);

			//connect to worker
			var remotePort = client.Connect<int>(msmqName1 + "/myport");
			//post some messages to see if the connection is working
			remotePort.Post(1);
			remotePort.Post(2);
			Thread.Sleep(200);
			Assert.AreEqual(2, receivedMessages);

			//server goes offline
			server.Dispose();

			//post some messages while server is offline
			remotePort.Post(3);
			remotePort.Post(4);

			//client goes offline
			Thread.Sleep(100);
			client.Dispose();
			Assert.AreEqual(2, receivedMessages);

			//restart server - should receive messages that have been sent while the server was offline
			server = new XcoAppSpace(@"msmq.queuename=" + msmqName1);
			server.Run<int>("myport", msg => Interlocked.Increment(ref receivedMessages));

			Thread.Sleep(200);
			Assert.AreEqual(4, receivedMessages);

			server.Dispose();
		}
	}
}
